package com.chenfan.mcn.component;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.chenfan.mcn.clients.baseinfo.BaseInfoClient;
import com.chenfan.mcn.extension.log.FieldChangeOperateLog;
import com.chenfan.mcn.clients.baseinfo.LogDTO;
import com.chenfan.common.extension.spring.TransactionUtils;
import com.chenfan.mcn.model.common.PageInfo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 单据操作日志处理者
 *
 * @author wulg
 * @date 2021-08-19
 **/
@Component
public class OperateLogHandler implements ApplicationContextAware {

    private static BaseInfoClient baseInfoClient;

    @Override
    public synchronized void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (baseInfoClient == null) {
            baseInfoClient = applicationContext.getBean(BaseInfoClient.class);
        }
    }

    /**
     * 查询操作日志
     * @param pageNum
     * @param pageSize
     * @param businessTypes
     * @param businessId
     * @return
     */
    public static PageInfo<FieldChangeOperateLog> selectLogs(Integer pageNum, Integer pageSize, Long businessId, List<Integer> businessTypes) {
        PageInfo<FieldChangeOperateLog> logs = baseInfoClient.getLog(new LogDTO().setId(businessId)
                .setBusinessTypes(businessTypes)
                .setPageNum(pageNum)
                .setPageSize(pageSize))
                .getObj();
        return logs;
    }

    /**
     * 插入操作日志
     *
     * @param operateLogs
     */
    public static void insertLog(List<FieldChangeOperateLog> operateLogs) {
        if(CollectionUtils.isEmpty(operateLogs)) {
            return;
        }
        TransactionUtils.afterCommit(() -> baseInfoClient.insertLog(operateLogs));
    }
}